<script lang="ts" setup>
import type {
  VxeGridListeners,
  VxeGridProps,
  VxeTablePropTypes,
} from '#/adapter/vxe-table';
import type { Kv } from '#/api';

import { ref, watch } from 'vue';

import { Button } from 'ant-design-vue';

import { useVbenVxeGrid } from '#/adapter/vxe-table';
import { useMessage } from '#/hooks/web/useMessage';
import { $t } from '#/locales';

interface Props {
  value: string | undefined;
}
interface Emits {
  (e: 'update:value', value: Kv[]): void;
}
const props = defineProps<Props>();
const emit = defineEmits<Emits>();
const { createConfirm } = useMessage();

const data = ref([]);
const editRules = ref<VxeTablePropTypes.EditRules>({});

const gridOptions = (): VxeGridProps => {
  return {
    toolbarConfig: {
      export: false,
      zoom: false,
      print: false,
      refresh: false,
      custom: false,
      buttons: [{ code: 'myInsert', name: '新增' }],
    },
    columns: [
      { title: $t('common.seq'), fixed: 'left', type: 'seq', width: 50 },
      {
        title: '参数名称',
        field: 'key',
        showOverflow: 'tooltip',
        align: 'center',
        editRender: {
          name: 'input',
          placeholder: '请点击输入',
          events: {
            change: () => {
              const recordset = gridApi.grid?.getRecordset();
              emit('update:value', [
                ...recordset.updateRecords,
                ...recordset.insertRecords,
              ]);
            },
          },
        },
      },
      {
        title: '值',
        field: 'value',
        showOverflow: 'tooltip',
        align: 'center',
        editRender: {
          name: 'input',
          placeholder: '请点击输入',
          events: {
            change: () => {
              const recordset = gridApi.grid?.getRecordset();
              emit('update:value', [
                ...recordset.updateRecords,
                ...recordset.insertRecords,
              ]);
            },
          },
        },
      },
      {
        field: 'action',
        fixed: 'right',
        title: '操作',
        slots: { default: 'action' },
        width: 150,
      },
    ],
    pagerConfig: { enabled: false },
    height: '250px',
    keepSource: true,
    formConfig: {
      enabled: false,
    },
    keyboardConfig: {
      isArrow: true,
      isDel: true,
      isEnter: true,
      isTab: true,
      isEdit: true,
      isChecked: true,
    },
    mouseConfig: { selected: true },
    editConfig: { trigger: 'dblclick', mode: 'cell', showStatus: true },
    proxyConfig: { enabled: false },
  };
};

const gridEvents: VxeGridListeners = {
  toolbarButtonClick({ code }) {
    switch (code) {
      case 'myInsert': {
        gridApi.grid?.insertAt({}, -1);

        const recordset = gridApi.grid?.getRecordset();
        emit('update:value', recordset?.insertRecords as Kv[]);
        break;
      }
      default: {
        break;
      }
    }
  },
};

const [Grid, gridApi] = useVbenVxeGrid({
  gridOptions: gridOptions(),
  gridEvents,
});

watch(
  () => props.value,
  (value: string | undefined) => {
    let paramList = [];
    if (value) {
      try {
        paramList = JSON.parse(value);
      } catch {}
    }
    data.value = paramList;

    emit('update:value', paramList);
  },
  { immediate: true },
);

function handleDelete(row: any) {
  createConfirm({
    iconType: 'warning',
    title: `您确定要删除吗？`,
    onOk: async () => {
      try {
        gridApi.grid?.remove(row);

        const recordset = gridApi.grid?.getRecordset();
        emit('update:value', recordset?.insertRecords as Kv[]);
      } catch {}
    },
  });
}
</script>

<template>
  <Grid :edit-rules="editRules" :data="data">
    <template #action="{ row }">
      <Button danger @click="handleDelete(row)">删除</Button>
    </template>
  </Grid>
</template>
